# Maintainer: Sven-Hendrik Haase <svenstaro@archlinux.org>
# Maintainer: George Rawlinson <grawlinson@archlinux.org>
# Contributor: Felix Fung <fylixeoi@gmail.com>

pkgname=timescaledb
_commit=2a39fbb444888bbba9139c7f7ab84f2aa28509ee
# limit to last 5 releases
_versions=(
  2.11.1
  2.11.2
  2.12.0
  2.12.1
  2.12.2 # current ts version
)
pkgver="${_versions[-1]}"
pkgrel=1
pkgdesc='An open-source time-series database optimized for fast ingest and complex queries'
arch=('loong64' 'x86_64')
url='https://www.timescale.com/'
license=('Apache' 'custom:Timescale')
depends=('postgresql<16' 'postgresql-libs<16' 'openssl')
makedepends=('gcc' 'cmake' 'git')
optdepends=(
  'timescaledb-tune: tune postgresql.conf for better performance'
  'timescaledb-old-upgrade: upgrade from previous major version of PostgreSQL'
)
install=timescaledb.install
source=("$pkgname::git+https://github.com/timescale/timescaledb#commit=$_commit")
sha512sums=('SKIP')

prepare() {
  mkdir build
}

build() {
  for version in "${_versions[@]}"; do
    cd "$srcdir/$pkgname"

    git checkout "$version"

    BUILD_DIR="$srcdir/build/$version" ./bootstrap \
      -DWARNINGS_AS_ERRORS=OFF \
      -DREGRESS_CHECKS=OFF \
      -DTAP_CHECKS=OFF \
      -DGENERATE_DOWNGRADE_SCRIPT=ON

    # build package or past shared library
    cd "$srcdir/build/$version"

    # ensure reproducible builds (value from `lsb_release -r`)
    # TODO: resolve https://github.com/timescale/timescaledb/issues/3480
    sed \
      -e "s:BUILD_OS_VERSION \".*\"$:BUILD_OS_VERSION \"rolling\":" \
      -i src/config.h

    if [ "$version" == "${_versions[-1]}" ]; then
      make
    else
      make timescaledb timescaledb-tsl sqlfile
    fi
  done
}

package() {
  cd "$pkgname"
  # install licenses from latest version
  git checkout "${_versions[-1]}"
  install -vDm644 -t "$pkgdir/usr/share/licenses/$pkgname" \
    LICENSE LICENSE-APACHE tsl/LICENSE-TIMESCALE

  # install package or past shared library
  for version in "${_versions[@]}"; do
    cd "$srcdir/build/$version"
    if [ "$version" == "${_versions[-1]}" ]; then
      make DESTDIR="$pkgdir/" install
    else
      install -vDm755 -t "$pkgdir/usr/lib/postgresql" \
        "src/$pkgname-$version.so" \
        "tsl/src/$pkgname-tsl-$version.so"
      install -Dm644 -t "$pkgdir/usr/share/postgresql/extension" \
        "sql/timescaledb--$version.sql"
    fi
  done
}
